package com.sh.data.engine.job.core.util;

import org.buildobjects.process.ProcBuilder;
import org.buildobjects.process.ProcResult;

import java.io.ByteArrayOutputStream;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;

public class CmdUtil {
    public static String[] runCmd(String cmd) throws Exception {

        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            ProcBuilder builder = new ProcBuilder("/bin/bash").withArgs("-c", cmd).withTimeoutMillis(600000);
            builder.withOutputStream(out);
            ProcResult result = builder.run();

            if (result.getExitValue() == 0) {
                String outStr = out.toString(StandardCharsets.UTF_8.name());
                return (outStr.split("\\r?\\n"));
            }

            String msg =
                String.format(
                    "execute command %s error, exitCode %s outStr %s errStr %s",
                    cmd,
                    result.getExitValue(),
                    result.getOutputString(),
                    result.getErrorString());
            throw new Exception(msg);
        }
    }

    public static int getProcessPid(Process process) throws Exception {
        Field field = process.getClass().getDeclaredField("pid");
        field.setAccessible(true);
        return (int) field.get(process);
    }
}
